package me.android.library.utils.android;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import java.lang.reflect.Field;
import java.util.Objects;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
@SuppressLint("ObsoleteSdkInt")
public class ViewUtil {

    public void getViewSize(final View view, final OnCalcSizeCallback callback) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewTreeObserver observer = view.getViewTreeObserver();

                // Android 16+ 使用新方法
                observer.removeOnGlobalLayoutListener(this);

                Size size = new Size();
                size.width = view.getWidth();
                size.height = view.getHeight();

                if (callback != null) {
                    callback.onCompleted(size);
                }
            }
        });
    }

    /**
     * 设置视图的背景为透明（优化版）
     *
     * @param view 要设置的视图
     */
    public void setTransparentBackground(View view) {
        if (view == null) return;

        // 使用 ContextCompat.getColor() 替代已弃用的 getResources().getColor()
        Context context = view.getContext();
        int transparentColor = ContextCompat.getColor(context, android.R.color.transparent);
        view.setBackgroundColor(transparentColor);

        // 或者直接使用 Color.TRANSPARENT（效果相同）
        // view.setBackgroundColor(android.graphics.Color.TRANSPARENT);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public void setDialogShowField(DialogInterface dialog, boolean closable) {
        try {
            Field field = Objects.requireNonNull(dialog.getClass().getSuperclass()).getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, closable);
        } catch (Exception ignored) {
        }
    }

    public void setFullScreen(Context cx, Dialog dialog) {
        setFullScreen(cx, dialog, Gravity.FILL);
    }

    /**
     * 设置全屏沉浸模式
     *
     * @param activity 当前活动的 Activity
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public void setFullScreenImmersive(Activity activity) {
        if (activity == null) {
            throw new IllegalArgumentException("Activity 不能为 null");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ (API 30+) 使用新 API
            setFullScreenForR(activity);
        } else {
            // Android 10 及以下使用旧 API
            setFullScreenForOld(activity);
        }
    }

    /**
     * Android 11+ (API 30+) 全屏实现
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    private void setFullScreenForR(Activity activity) {
        // 获取窗口Insets控制器
        WindowInsetsController insetsController = activity.getWindow().getInsetsController();
        if (insetsController != null) {
            // 隐藏状态栏和导航栏
            insetsController.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());

            // 设置系统栏行为：滑动时临时显示，几秒后自动隐藏
            insetsController.setSystemBarsBehavior(
                    WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            );
        }

        // 允许布局延伸到系统栏区域
        activity.getWindow().setDecorFitsSystemWindows(false);
    }

    /**
     * Android 10 及以下版本全屏实现
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    private void setFullScreenForOld(Activity activity) {
        // 获取 DecorView
        View decorView = activity.getWindow().getDecorView();

        // 组合系统 UI 标志
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // 布局延伸到状态栏
                | View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // 布局延伸到导航栏
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // 隐藏导航栏
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; // 粘性沉浸：滑动显示后自动隐藏

        // 设置 UI 标志
        decorView.setSystemUiVisibility(uiOptions);

        // 允许布局延伸到系统栏区域（部分旧设备需要）
        activity.getWindow().setDecorFitsSystemWindows(false);
    }

    /**
     * 退出全屏模式（恢复系统栏显示）
     *
     * @param activity 当前活动的 Activity
     */

    @RequiresApi(api = Build.VERSION_CODES.R)
    public void exitFullScreen(Activity activity) {
        if (activity == null) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 恢复显示
            WindowInsetsController insetsController = activity.getWindow().getInsetsController();
            if (insetsController != null) {
                insetsController.show(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
            }
            activity.getWindow().setDecorFitsSystemWindows(true);
        } else {
            // Android 10 及以下恢复显示
            View decorView = activity.getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            activity.getWindow().setDecorFitsSystemWindows(true);
        }
    }

    // -----------------------------------------------Dialog----------------------------------------------

    /**
     * 设置对话框全屏显示（优化版）
     *
     * @param cx      上下文
     * @param dialog  对话框实例
     * @param gravity 对齐方式（如 Gravity.CENTER）
     */
    public void setFullScreen(Context cx, Dialog dialog, int gravity) {
        if (!(cx instanceof Activity) || dialog == null) return;

        Window window = dialog.getWindow();
        if (window == null) return;

        // 设置对话框位置
        window.setGravity(gravity);

        // 获取窗口属性
        WindowManager.LayoutParams lp = window.getAttributes();

        // 获取屏幕尺寸（兼容新旧 API）
        WindowManager windowManager = ((Activity) cx).getWindowManager();
        int width, height;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+：使用 WindowMetrics 获取真实尺寸
            WindowInsets windowInsets = windowManager.getCurrentWindowMetrics().getWindowInsets();
            width = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()).right
                    - windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()).left;
            height = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()).bottom
                    - windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()).top;
        } else {
            // Android 5.0-10：使用 DisplayMetrics 获取尺寸
            android.util.DisplayMetrics metrics = new android.util.DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
        }

        // 设置对话框宽高
        lp.width = width;
        lp.height = height;
        window.setAttributes(lp);
    }

    public void scrollTop(final ScrollView sv) {

        sv.postDelayed(new Runnable() {
            @Override
            public void run() {
                sv.fullScroll(ScrollView.FOCUS_UP);
            }
        }, 50);
    }

    public void scrollBottom(final ScrollView sv) {
        sv.postDelayed(new Runnable() {
            @Override
            public void run() {
                sv.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }, 50);
    }


    // -----------------------------------------------ViewPager----------------------------------------------

    // ViewPager（旧版）设置滚动速度
    public void setViewPagerScrollDuration(ViewPager viewPager, int durationMs) {
        try {
            // 获取 mScroller 字段
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);

            // 获取系统默认的 Interpolator（DecelerateInterpolator）
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);
            Interpolator defaultInterpolator = (Interpolator) interpolatorField.get(null);

            // 创建自定义 Scroller
            FixedSpeedScroller scroller = new FixedSpeedScroller(
                    viewPager.getContext(),
                    defaultInterpolator != null ? defaultInterpolator : new LinearInterpolator()
            );
            scroller.setDuration(durationMs);

            // 设置到 ViewPager
            scrollerField.set(viewPager, scroller);
        } catch (Exception ignored) {
        }
    }

    public interface OnCalcSizeCallback {
        void onCompleted(Size size);
    }

    public static class Size {
        public int width, height;
    }

    // 自定义 Scroller 类（用于 ViewPager）
    private static class FixedSpeedScroller extends android.widget.Scroller {
        private int mDuration = 500; // 默认 500ms

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        public void setDuration(int duration) {
            this.mDuration = duration;
        }
    }
}




